import React, { useState, useEffect, useRef, useCallback, useContext } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import { Button, Input, Space, Table } from 'antd';
import Highlighter from 'react-highlight-words';
import { useHistory } from 'react-router-dom';
import { openNotification_util, fetchsync_util, dealnullorundenfined } from '../util/util.js'
//import {Context} from '../scjh/zjh_form'

const { Search } = Input;
var storage = window.localStorage;

const Popup_table_hooks_datas = (props) => {
  const history = useHistory();
  const [selectionType, setSelectionType] = useState(props.selecttype);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [tabledata, settabledata] = useState([])
  const [ifshow, setifshow] = useState(props.ifshow)
  const [isExactMatch, setIsExactMatch] = useState(false);
  
  // 支持外部触发打开 popup
  useEffect(() => {
    if (props.triggerOpen === true) {
      setifshow("block")
      // 重置 triggerOpen，避免重复触发
      if (props.onTriggered) {
        props.onTriggered()
      }
    }
  }, [props.triggerOpen, props.onTriggered])

  //const {wlmcdatasource} = useContext(Context);


  // rowSelection object indicates the need for row selection
  const rowSelection = {
    selectedRowKeys: selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setselectedRows(selectedRows)
      setselectedRowKeys(selectedRowKeys)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
    setIsExactMatch(false);
  };
  const handleSearchExact = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
    setIsExactMatch(true);
  };
  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
    setSearchedColumn('');
    setIsExactMatch(false);
  };

  //row双击s
  const onRowSelect = (record, index) => {
    return {
      onDoubleClick: (e) => {
        if (props.sfdoubleclick) {
          storage[props.storagekey] = JSON.stringify(record)
          history.push({ pathname: props.doubleclickroute });
        }
        else;
      }
    }
  };

  const getColumnSearchProps = (dataIndex, title) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }) => (
      <div
        className="popup-filter-dropdown"
        style={{
          padding: 16,
          zIndex: 1060, // 确保在 popup 之上（popup 最高 z-index 是 1052）
          position: 'relative',
        }}
        onKeyDown={(e) => e.stopPropagation()}
      >
        <Input
          ref={searchInput}
          placeholder={`搜索${title}`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{
            marginBottom: 8,
            display: 'block',
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            搜索
          </Button>
          <Button
            type="primary"
            onClick={() => handleSearchExact(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{
              width: 90,
            }}
          >
            精准搜索
          </Button>
          <Button
            onClick={() => {
              if (clearFilters) handleReset(clearFilters);
            }}
            size="small"
            style={{
              width: 90,
            }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: "#0885fb" }}
            onClick={() => {
              confirm({
                closeDropdown: false,
              });
              setSearchText(selectedKeys[0]);
              setSearchedColumn(dataIndex);
            }}
          >
            过滤
          </Button>
          <Button
            type="link"
            size="small"
            style={{ color: "#0885fb" }}
            onClick={() => {
              close();
            }}
          >
            关闭
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined
        style={{
          color: filtered ? '#f0721f' : '#0885fb',
        }}
      />
    ),
    onFilter: (value, record) => {
      if (!record[dataIndex]) return false;
      const recordValue = record[dataIndex].toString().toLowerCase();
      const searchValue = value.toString().toLowerCase();
      
      // 如果当前列是搜索列且是精准匹配模式，使用精准匹配
      if (searchedColumn === dataIndex && isExactMatch) {
        return recordValue === searchValue;
      }
      // 否则使用模糊匹配
      return recordValue.includes(searchValue);
    },
    onFilterDropdownOpenChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current ? searchInput.current.select() : 1, 100);
      }
    },
    render: (text) =>
      searchedColumn === dataIndex && searchText ? (
        <Highlighter
          highlightStyle={{
            backgroundColor: '#ffc069',
            padding: 0,
          }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ''}
        />
      ) : (
        text
      ),
  });

  const colnumsorigin = props.tablecolnum
  const columns = colnumsorigin.map(item => {
    return {
      title: item.title,
      dataIndex: item.key,
      key: item.key,
      ...getColumnSearchProps(item.key, item.title),

    }
  })




  useEffect(() => {
    settabledata(dealnullorundenfined(props.datas))
  }, [props.datas])


  // 初始化已选中的数据
  useEffect(() => {
    if (ifshow === "block" && props.selectedData && props.selectedData.length > 0 && tabledata.length > 0) {
      // 根据已选数据初始化选中状态
      // 需要根据唯一标识（如 gysmc 或 gysid）来匹配
      const matchKey = props.matchKey || 'value' // 默认使用 value 字段作为匹配键
      const selectedKeys = []
      const selectedRowsData = []
      
      tabledata.forEach((record, index) => {
        const isSelected = props.selectedData.some(selected => {
          // 支持多种匹配方式：gysmc、gysid、wlbm、wlmc 或 value
          if (props.matchFields) {
            // 对于物料明细（wlbm），如果 matchFields 包含 wlbm，则只使用 wlbm 和 id 匹配，不使用 wlmc
            // 这样可以避免同名物料被同时选中
            const hasWlbm = props.matchFields.includes('wlbm')
            const hasWlmc = props.matchFields.includes('wlmc')
            
            if (hasWlbm && hasWlmc) {
              // 如果同时包含 wlbm 和 wlmc，则过滤掉 wlmc，只使用 wlbm 和 id 匹配
              const fieldsToMatch = props.matchFields.filter(field => field !== 'wlmc')
              return fieldsToMatch.some(field => {
                const recordValue = record[field]
                let selectedValue = selected[field]
                if (!selectedValue) {
                  if (field === 'gysid' || field === 'wlbm') {
                    selectedValue = selected.value
                  } else {
                    selectedValue = selected[field]
                  }
                }
                return recordValue && selectedValue && String(recordValue) === String(selectedValue)
              })
            } else {
              // 如果指定了多个匹配字段，只要有一个匹配就认为已选中
              return props.matchFields.some(field => {
                const recordValue = record[field]
                // 支持多种字段映射：gysid -> value, wlbm -> value
                let selectedValue = selected[field]
                if (!selectedValue) {
                  if (field === 'gysid' || field === 'wlbm') {
                    selectedValue = selected.value
                  } else {
                    selectedValue = selected[field]
                  }
                }
                return recordValue && selectedValue && String(recordValue) === String(selectedValue)
              })
            }
          } else {
            // 默认使用 matchKey 字段匹配
            const recordValue = record[matchKey]
            const selectedValue = selected[matchKey] || selected.value
            return recordValue && selectedValue && String(recordValue) === String(selectedValue)
          }
        })
        
        if (isSelected) {
          // 使用 value 字段作为 key，如果没有则尝试使用其他唯一标识（wlbm, gysid, id, key）
          // 对于物料明细，优先使用 wlbm 作为 rowKey，确保唯一性
          let rowKey
          if (props.matchFields && props.matchFields.includes('wlbm')) {
            rowKey = record.wlbm || record.id || record.value || record.key || index
          } else if (props.matchFields && props.matchFields.includes('gysid')) {
            rowKey = record.gysid || record.id || record.value || record.key || index
          } else {
            rowKey = record.value || record.wlbm || record.gysid || record.id || record.key || index
          }
          selectedKeys.push(rowKey)
          selectedRowsData.push(record)
        }
      })
      
      setselectedRowKeys(selectedKeys)
      setselectedRows(selectedRowsData)
    } else if (ifshow === "none") {
      // 关闭时清空选中状态
      setselectedRowKeys([])
      setselectedRows([])
    }
  }, [ifshow, props.selectedData, tabledata, props.matchKey, props.matchFields])

  //送回数据
  const sendbackdata = async () => {
    if (selectedRows.length == 0) { openNotification_util("未选择数据") }
    else {
      // 根据选择类型决定返回格式：
      // - checkbox（多选）：返回整个数组（用于 muti-free 方法）
      // - radio（单选）：返回单个对象（用于 muti 方法）
      const dataToSend = selectionType === 'checkbox' ? selectedRows : selectedRows[0]
      props.handlechange(dataToSend)
      props.changefresh ? props.changefresh() : null

      setifshow("none")
    }
  }

  return (
    <div>
      {!props.hideInput && (
        <Input style={{ width: "95%", backgroundColor: "#F2F7FF" }} placeholder="请选择" value={props.inputvalue} onClick={() => { setifshow("block") }} />
      )}
      <div style={{
        position: "fixed", backgroundColor: "rgba(0,0,0,0.8)",
        width: "100vw", left: "0%", top: "0%", zIndex: "1050", display: ifshow
      }}>

        <div style={{
          position: "absolute", backgroundColor: "white", height: "90vh",
          width: "95%", left: "2.5%", top: "5vh", zIndex: "1051", 
          borderRadius: "8px", boxShadow: "0 8px 32px rgba(0,0,0,0.3)"
        }}>


          <div style={{ 
            position: "absolute", 
            top: "1rem", 
            left: "1rem", 
            right: "1rem", 
            zIndex: "1052",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            padding: "0.5rem 0",
            borderBottom: "1px solid #e8e8e8"
          }}>
            <div style={{ fontWeight: "600", fontSize: "16px", color: "#333" }}>
              {props.popup_maintitle}
            </div>
            <div>
              <Button style={{ marginRight: "0.5rem" }} onClick={() => {
                props.changefresh ? props.changefresh() : null
                setifshow("none")
              }}>关闭</Button>
              <Button type="primary" onClick={sendbackdata}>返回数据</Button>
            </div>
          </div>
          
          <div style={{ 
            position: "absolute", 
            top: "4rem", 
            left: "1rem", 
            right: "1rem", 
            bottom: "1rem",
            overflow: "auto",
            zIndex: 1053 // 确保表格容器在 popup 内容之上
          }}>
            <Table columns={columns} dataSource={tabledata} style={{ width: "100%", height: "100%" }}
            onRow={onRowSelect}
            rowKey={(record) => {
              // 对于物料明细，优先使用 wlbm 作为 rowKey，确保唯一性
              if (props.matchFields && props.matchFields.includes('wlbm')) {
                return record.wlbm || record.id || record.value || record.key || record.gysid
              }
              // 对于供应商明细，优先使用 gysid 作为 rowKey
              if (props.matchFields && props.matchFields.includes('gysid')) {
                return record.gysid || record.id || record.value || record.key || record.wlbm
              }
              return record.value || record.id || record.key || record.gysid || record.wlbm
            }}
            //每页显示15条
            pagination={{ pageSize: 15 }}
            size="small"
            rowSelection={{
              type: selectionType,
              ...rowSelection,
            }}
            getPopupContainer={(triggerNode) => {
              // 返回 popup 的主容器，确保下拉框在 popup 内
              const popupContainer = triggerNode.closest('[style*="zIndex: 1051"]');
              return popupContainer || triggerNode.parentElement;
            }}
            className="custom-table-styles popup-table-with-filter" />
          </div>
        </div>
      </div>

    </div>
  )

}


export default Popup_table_hooks_datas




var styles = {
  maincontainer: { height: "90%", width: "99%", backgroundColor: `#F1F1F1` }
}

// 添加全局样式，确保搜索下拉框在 popup 之上显示
if (typeof document !== 'undefined') {
  const style = document.createElement('style');
  style.textContent = `
    .popup-table-with-filter .ant-table-filter-dropdown {
      z-index: 1060 !important;
    }
    .popup-filter-dropdown {
      z-index: 1060 !important;
    }
  `;
  if (!document.head.querySelector('style[data-popup-filter]')) {
    style.setAttribute('data-popup-filter', 'true');
    document.head.appendChild(style);
  }
}



